
#include <stdio.h> 
#include <boost/asio.hpp>
#include "System.h"
#include "convert.h"

using namespace boost::asio;

namespace Util {

string CSystem::mHostName;
string CSystem::mHostIPAddress;

string& CSystem::GetHostName()
{
	if(mHostName.length() == 0) {
		char host_name[255]; 
		if (gethostname(host_name, sizeof(host_name)) != SOCKET_ERROR) {
			CConverter::Ascii_TO_UTF8(string(host_name), mHostName);
		} 
	}

	return mHostName;
}

string& CSystem::GetHostIPAddress()
{
	int try_count = 0;

	do {
		if(mHostIPAddress.length() == 0) {
			boost::asio::io_service ioserv;
			ip::tcp::resolver resolver(ioserv);
			ip::tcp::resolver::query query("www.baidu.com", "http");
			ip::tcp::socket socket(ioserv);
			boost::asio::connect(socket, resolver.resolve(query));
			if(socket.is_open()) {
				mHostIPAddress = socket.local_endpoint().address().to_string();
			}
		}
		else {
			string ascii_host_name;
			CConverter::UTF8_TO_Ascii(GetHostName(), ascii_host_name);
			bool found = false;
			struct hostent *phe = gethostbyname(ascii_host_name.c_str());
			for (int i = 0; phe && phe->h_addr_list[i] != 0; ++i) { 
				struct in_addr addr; 
				memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));
				if(mHostIPAddress == inet_ntoa(addr)) {
					found = true;
					break;
				}
			} 
			if(!found) mHostIPAddress.clear();
		}

	} while(mHostIPAddress.length() == 0 && try_count++ < 3);

	return mHostIPAddress;
}

}